package com.cloudz.iptv.http;

import android.os.Handler;
import android.support.annotation.NonNull;

import com.cloudz.iptv.api.v1.UpdateService;
import com.cloudz.iptv.utils.InPutJson;
import com.cloudz.iptv.utils.ResponseUtils;
import com.cloudz.iptv.utils.RetrofitUtils;
import com.cloudz.iptv.utils.download.DownloadListener;
import com.cloudz.iptv.utils.download.DownloadUtil;
import com.vector.update_app.HttpManager;

import java.io.File;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * @File Name: com.cloudz.iptv.http
 * @Author: YJ //作者及
 * @Date: 2019/3/8 12:08 AM//完成日期
 * @Description: // 描述
 * @Version: v0.0.1 // 版本信息
 * @Function List: // 主要函数及其功能
 * @Others: // 其它内容的说明
 * @History: // 历史修改记录
 */
public class UpdateAppHttpUtil implements HttpManager
{

    private String baseUrl;

    /**
     * 异步get
     *
     * @param url      get请求地址
     * @param params   get参数
     * @param callBack 回调
     */
    @Override
    public void asyncGet(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack)
    {

        this.baseUrl = url;

        // 验证绑定情况
        UpdateService updateService = RetrofitUtils.getInstance().createApi(url + "/iptv/res/", UpdateService.class);

        updateService.update(params.get("token"), params.get("deviceId") + "", params.get("appVersion") + "").enqueue(new retrofit2.Callback<ResponseBody>()
        {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
            {
                try
                {
                    InPutJson inOutJson = ResponseUtils.getInOutJson(response);

                    if (inOutJson.result)
                    {
                        callBack.onResponse(inOutJson.data);
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {
                callBack.onError("请求更新错误");
            }
        });
    }

    /**
     * 异步post
     *
     * @param url      post请求地址
     * @param params   post请求参数
     * @param callBack 回调
     */

    @Override
    public void asyncPost(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack)
    {

    }

    final Handler handler = new Handler();

    /**
     * 下载
     *
     * @param url      下载地址
     * @param path     文件保存路径
     * @param fileName 文件名称
     * @param callback 回调
     */
    @Override
    public void download(@NonNull String url, @NonNull String path, @NonNull String fileName, @NonNull FileCallback callback)
    {

        DownloadUtil.download(baseUrl, url, path + File.separator + "update.apk", new DownloadListener()
        {
            @Override
            public void onStart()
            {
//                callback.onBefore();
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.onBefore();
                    }
                });
            }

            @Override
            public void onProgress(float progress, long total)
            {
                callback.onProgress(progress, total);
//                handler.post(new Runnable() {
//                    @Override
//                    public void run()
//                    {
//                        callback.onProgress(progress, total);
//                    }
//                });
            }

            @Override
            public void onFinish(String path, File file)
            {
//                callback.onResponse(file);
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.onResponse(file);
                    }
                });
            }

            @Override
            public void onFail(String errorInfo)
            {
//                callback.onError("下载失败");
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.onError("下载失败");
                    }
                });
            }
        });

//        DownLoadFileServiceApi downLoadFileServiceApi = RetrofitUtils.getInstance().createApi("http://192.168.2.23:8089", DownLoadFileServiceApi.class);
//
//        downLoadFileServiceApi.downloadApk(url).enqueue(new RetrofitCallback<ResponseBody>()
//        {
//            @Override
//            public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response)
//            {
//
//                try
//                {
//
//                    InputStream is = response.body().byteStream();
//                    //获取文件总长度
//                    long totalLength = response.body().contentLength();
//
//                    File file = new File(path, "update.apk");
//                    if (!file.exists())
//                    {
//                        file.getParentFile().mkdirs();
//                    } else {
//                        file.delete();
//                    }
//                    FileOutputStream fos = new FileOutputStream(file);
//                    BufferedInputStream bis = new BufferedInputStream(is);
//                    byte[] buffer = new byte[1024];
//                    int len;
//                    long currentLength = 0;
//                    while ((len = bis.read(buffer)) != -1)
//                    {
//                        fos.write(buffer, 0, len);
//                        //此处进行更新操作
//                        currentLength += len;
//                        //len即可理解为已下载的字节数
//                        callback.onProgress(100 * currentLength / totalLength, totalLength);
//                    }
//                    fos.flush();
//                    fos.close();
//                    bis.close();
//                    is.close();
//
//                    callback.onResponse(file);
//                } catch (Exception e)
//                {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onFailure(Call<ResponseBody> call, Throwable t)
//            {
//                callback.onError("下载失败");
//            }
//
//            @Override
//            public void onLoading(long total, long progress)
//            {
//                callback.onProgress(progress, total);
//            }
//        });
    }
}
